<template>
	<div class="thePage">
		<van-form @submit="onSubmit">
			<van-field v-model="loginForm.name" name="name" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
			<van-field v-model="loginForm.password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
			<div style="margin: 16px;"><van-button block type="primary" native-type="submit">提交</van-button></div>
		</van-form>

		<div><van-button @click="onRegister">若还没账号，点击前往注册</van-button></div>
	</div>
</template>

<script>
//1.导入封装后的接口
import { loginAPI } from '@/api/user.js';
import * as Auth from "@/utils/auth.js" //导入本地存储方法
export default {
	name: 'Login',
	data() {
		return {
			loginForm: { name: 'dingding', password: '123456' }
		};
	},
	//在生命周期函数中调用API接口从后端取业务数据
	created() {
		//使用封装的方法，从本地存储中获取用户名
		this.loginForm.name = Auth.getUserLocal().name;
	},

	methods: {
		onSubmit() {
			//console.log('submit', this.loginForm);
			//准备参数
			let params = {
				name: this.loginForm.name,
				password: this.loginForm.password
			};
			//调用接口
			loginAPI(params).then(result => {
				console.log(result);
				this.$toast({ message: '登录成功！', duration: 1000 });
				//把用户token及其他信息保存在本地
				//把返回的 user 、token 在本地保存
				Auth.setTokenLocal(result.data.token); //保存Token
				Auth.setUserLocal(result.data.user); //保存用户数据
				
				//实现路由跳转页面 看看当前路由是否指定有重定向地址 否则跳转 user
				let toPath = this.$route.params.redirect || "user";
				//延时1秒后路由跳转
				setTimeout(() => {
				  this.$router.replace({
				    path: toPath
				  });
				}, 1000);
				
			});
		},

		onRegister() {
			//路由跳转
			this.$router.push({ name: 'register' });
		}
	}
};
</script>

<style lang="less" scoped="scoped">
.thePage {
	margin: 100px 20px;
}
</style>
